import Singleton from "../base/Singleton";

interface Iitem {
    func: Function
    ctx: unknown
}

/** 事件中心 */
export default class EventCenter extends Singleton {
    static get instance() {
        return super.GetInstance<EventCenter>();
    }
    private eventDic: Map<string, Array<Iitem>> = new Map();
    on(eventName: string, func: Function, ctx?: unknown) {
        if (this.eventDic.has(eventName)) {
            const items = this.eventDic.get(eventName);
            if (items) {
                items.push({ func, ctx });
            }
        } else {
            this.eventDic.set(eventName, [{ func, ctx }])
        }
    }
    off(eventName: string, func: Function, ctx?: unknown) {
        if (this.eventDic.has(eventName)) {
            const items = this.eventDic.get(eventName);
            if (items) {
                const index = items.findIndex(i => i.func === func && i.ctx === ctx);
                index > -1 && items.splice(index, 1);
            }
        }
    }
    emit(eventName: string, ...params: unknown[]) {
        if (this.eventDic.has(eventName)) {
            this.eventDic.get(eventName)?.forEach(({ func, ctx }) => {
                ctx ? func.apply(ctx, params) : func(...params);
            })
        }
    }
    clear() {
        this.eventDic.clear();
    }
}